const uploadWeixinCode = require('upload_wx_code');
const {readFile,writeFile,dealWithUplaodPath,deteFormat} = require('./common')
// // console.log(uploadWeixinCode);
// uploadWeixinCode({
//     keyFileListPath:'F:/Program Files/七件事项目文件/前端打包资料/前端档案库/frontEndAchive/微信小程序上传资料/开元禅 已关闭白名单',//待上传的打包文件的key秘钥
//     buildFileListPath:'F:/Program Files/七件事项目文件/projectBuild/uni-build/dist/build',//待上传的打包文件的上一级 或上上一级路径
// })
const cmd = require('node-cmd');
const compressing = require("compressing");
//打包日志收集
const log = {
    'projectName':{
        wx:{
            date:'2021年7月28日17:12:54',
            buildReslut:'打包结果',
            uoloadCode:'代码上传信息，如果没有传 wxKeyPath 则自动为空'
        }
    }
}

//已打包的次数
let buildCount = 0;
//原packageJson文件
let originPackageJson = ""
// const origin
//批量打包 

let curBuildInfo ={
    device:"",//区分当前打包的是哪个端
    project:'',//当前打包的项目名
    path:'',//当前端打包后所在的文件
}

//打包完所在的路径
let root = "dist";//默认dist

//监听程序退出
async function exitHandler(options, exitCode) {
    console.log('复原Package.json');
    await writeFile(originPackageJson.data);
    if (options.exit) process.exit();
};
process.on('SIGINT', exitHandler.bind(null, {exit:true}));

// init(buildPath)
//打包初始化
async function init(buildPath){
   const {projectName,wx = false,h5 = false,options} = buildPath;
   const {wxKeyPath = "",H5compressing = false } = options;
   root = options.root || 'dist';
   curBuildInfo.project = projectName;
   if (wx) {
       //打包微信
       curBuildInfo.device = "mp-weixin";
       curBuildInfo.path = `${root}/${projectName}/mp-weixin`;
       console.log('开始打包wx代码');
       await configuration(projectName,'mp-weixin');
       //把原来的 package.json写回去
       await writeFile(originPackageJson.data);
       if (wx && wxKeyPath) {
        //准备上传 wx 小程序
       const uploadWxCode = await uploadWeixinCode({
            keyFileListPath:wxKeyPath,//待上传的打包文件的key秘钥
            buildFileListPath:`${dealWithUplaodPath()}/${root}/${projectName}`,//待上传的打包文件的上一级 或上上一级路径
        });
        //记录上传结果
        log[projectName]['mp-weixin']['wxCodeUploadReslut'] = uploadWxCode;
      }
   }
   if (h5) {
       console.log('开始打包h5');
       curBuildInfo.device = "h5";
       curBuildInfo.path = `${root}/${projectName}/h5`;
       await configuration(projectName,'h5');
       await writeFile(originPackageJson.data);
       //是否压缩打包后的代码
       if (H5compressing) {
          compressing.zip.compressDir(`${dealWithUplaodPath()}/${root}/${projectName}/h5`,`${dealWithUplaodPath()}/${root}/${projectName}/h5.zip`)
       }
  };
  //还需要判断微信的包是否已经打包成功了
  console.log('打包成功',log); 
  if (log) {
     writeFile(JSON.stringify(log, null, 4),"./results.json");
  }
  //代码已完成上传操作
  return log;
}

//修改文件并且重新写入文件，然后根据配置去打包 
 async function configuration (){
   let buildParmas = await modifyPackageJSON();
   const {code} = buildParmas;
   if (code == 0) {
       await startBuild()
   }else{
       return {code:-1}
   }
};
//修改package.json
async function modifyPackageJSON(){
    let fileContent = await readFile();
    if (fileContent.code == -1){
        console.log('读取文件失败：'+ fileContent.data);
        return {
            code:-1,
            data:'读取文件失败：'+ fileContent.data
        }
    };
    //如果是第一次打包
    if(buildCount == 0){
        //保存原json文件
        originPackageJson = fileContent;
    };
    let updFile = fileContent.data.replace(`UNI_PLATFORM=${curBuildInfo.device}`,`UNI_PLATFORM=${curBuildInfo.device} UNI_OUTPUT_DIR=${curBuildInfo.path}`);
    let resluts = await writeFile(updFile);
    if (resluts.code == 0) {
        buildCount+=1;
        console.log('写入成功，开始打包');
        return {code:0}
    }else{
        return {
            code:-1,
            data:'修改写入失败 禁止打包'
        }
    }
}

//开始执行打包
function startBuild(){
    const {project,device,path} = curBuildInfo;
    return new Promise((resolve,reject) =>{
        cmd.run(`cd ../ & npm run build:${device}`,
             function(err, data, stderr){
                 if (!log[project]) {
                    log[project] = {};
                 };
                 if (err !== null) {
                     console.log(err);
                     log[project][device] = {
                         dete:deteFormat(),
                         result:`${project}打包${device}端失败，请执行 脚本命令查看报错信息`
                     }
                     reject({code:-1})
                 }else{
                     log[project][device] =  {
                        dete:deteFormat(),
                        result:`${project}打包${device}端成功,文件路径${path}`
                    }
                     resolve({code:0})
                 }
             }
        );
    })
};


module.exports = init